package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.CutterLifeCycleDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.CutterLifeCycleForm;
import com.wing.cabinet.model.response.CutterLifeCycleVO;
import com.wing.common.exception.BusinessException;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 刀具生命周期-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class CutterLifeCycleServiceImpl extends ServiceImpl<CutterLifeCycleDao, CutterLifeCycle> implements CutterLifeCycleService {

    @Autowired
    private UseInventoryUserKnifeService useInventoryUserKnifeService;
    @Autowired
    private CutterLifeCycleRecordService cutterLifeCycleRecordService;
    @Autowired
    private CheckedResultService checkedResultService;
    @Autowired
    private ProductDetailService productDetailService;

    @Override
    public int add(CutterLifeCycleForm cutterLifeCycleForm) {

        //校验

        CutterLifeCycle cutterLifeCycle =new CutterLifeCycle();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CutterLifeCycle.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(cutterLifeCycleForm, cutterLifeCycle, copyOptions);

        return baseMapper.insert(cutterLifeCycle);
    }

    @Override
    public List<CutterLifeCycleVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<CutterLifeCycleVO> pageList4app(Page page, Map<String, Object> params) {
        List<CutterLifeCycleVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public CutterLifeCycleVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    @Transactional(readOnly = false)
    public void addLifeCycle(List<String> labelCodeList, CutterLifeCycle.Status status, StorageInventoryInout.BusinessDetailType businessDetailType, UseInventoryInout.BusinessType useBusinessType, String code, String deviceCode) {
        for (String labelCode : labelCodeList) {
            // 查询条码数据
            UseInventoryUserKnife useInventoryUserKnife = useInventoryUserKnifeService.getOne(new QueryWrapper<UseInventoryUserKnife>().eq("code", labelCode));
            if(useInventoryUserKnife == null){
                throw new BusinessException(300, "条码数据不存在");
            }
            if(StringUtils.isBlank(useInventoryUserKnife.getSkuCode())){
                throw new BusinessException(300, "数据缺失");
            }
            // 查询该条码是否已经生成刀具生命周期
            CutterLifeCycle cutterLifeCycle = baseMapper.selectOne(new QueryWrapper<CutterLifeCycle>().eq("pack_label_code", labelCode));
            if(null != cutterLifeCycle){
                if(status.equals(CutterLifeCycle.Status.takeOut)){
                    cutterLifeCycle.setStatus(CutterLifeCycle.Status.inUse);
                }else if(status.equals(CutterLifeCycle.Status.tradeIn)){ // 以旧换新
                    if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempInByOldNew)){ // 以旧换新存入暂存
                        cutterLifeCycle.setStatus(CutterLifeCycle.Status.tradeInTemporaryStorage);
                    }else if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairInByOldNew)){ // 以旧换新存入维修
                        cutterLifeCycle.setStatus(CutterLifeCycle.Status.tradeInRepair);
                    }else if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleInByOldNew)){ // 以旧换新存入报废
                        cutterLifeCycle.setStatus(CutterLifeCycle.Status.tradeInScrap);
                    }
                }else{
                    cutterLifeCycle.setStatus(status);
                }
                cutterLifeCycle.setCurOperatorId(JwtUtils.getLoginUserId());
                cutterLifeCycle.setCurOperatorName(JwtUtils.getLoginUsername());
                if(status.equals(CutterLifeCycle.Status.check) || status.equals(CutterLifeCycle.Status.checkForTemporaryStorage)
                        || status.equals(CutterLifeCycle.Status.checkForRepair) || status.equals(CutterLifeCycle.Status.checkForScrap)
                        || status.equals(CutterLifeCycle.Status.checkForLoss) || status.equals(CutterLifeCycle.Status.checkForSpecDiscrepancy)){ // 盘验
                    cutterLifeCycle.setIsCheck(CutterLifeCycle.IsCheck.yes);
                    cutterLifeCycle.setInspectorId(JwtUtils.getLoginUserId());
                    cutterLifeCycle.setInspectorName(JwtUtils.getLoginUsername());
                }
                baseMapper.updateById(cutterLifeCycle);
            }else{
                if(status.equals(CutterLifeCycle.Status.getFresh) || status.equals(CutterLifeCycle.Status.batchInUse)
                        || (status.equals(CutterLifeCycle.Status.tradeIn) && null != useBusinessType && useBusinessType.equals(UseInventoryInout.BusinessType.cellCabOutByOldNew))){ // 添加刀具生命周期的第一步骤一定是领新 || 批量导入在用 || 售刀柜领取(以旧换新)
                    // 添加刀具生命周期
                    cutterLifeCycle = new CutterLifeCycle();
                    cutterLifeCycle.setCreator(JwtUtils.getLoginUserId());
                    cutterLifeCycle.setCreatorName(JwtUtils.getLoginUsername());
                    cutterLifeCycle.setPackLabelCode(labelCode);
                    // 通过skuCode查询数据
                    ProductDetailVO productDetailVO = productDetailService.getProductDetailBySkuCode(useInventoryUserKnife.getSkuCode());
                    cutterLifeCycle.setSkuCode(productDetailVO.getSkuCode());
                    cutterLifeCycle.setSkuName(productDetailVO.getSkuName());
                    cutterLifeCycle.setSpecCode(productDetailVO.getOldSpecCode());
                    cutterLifeCycle.setUsherInId(JwtUtils.getLoginUserId());
                    cutterLifeCycle.setUsherInName(JwtUtils.getLoginUsername());
                    if(status.equals(CutterLifeCycle.Status.batchInUse)){
                        cutterLifeCycle.setStatus(CutterLifeCycle.Status.batchInUse);
                    }else{
                        cutterLifeCycle.setStatus(CutterLifeCycle.Status.inUse); // 如果添加的生命周期是领新的，就直接让他的状态为在用
                    }
                    cutterLifeCycle.setCurOperatorId(JwtUtils.getLoginUserId());
                    cutterLifeCycle.setCurOperatorName(JwtUtils.getLoginUsername());
                    cutterLifeCycle.setIsCheck(CutterLifeCycle.IsCheck.no);
                    baseMapper.insert(cutterLifeCycle);
                }else{
                    break;
                }
            }

            // 添加刀具生命周期记录
            CutterLifeCycleRecord cutterLifeCycleRecord = new CutterLifeCycleRecord();
            cutterLifeCycleRecord.setCreator(JwtUtils.getLoginUserId());
            cutterLifeCycleRecord.setCreatorName(JwtUtils.getLoginUsername());
            cutterLifeCycleRecord.setCutterLifeCycleId(cutterLifeCycle.getId());
            cutterLifeCycleRecord.setTime(LocalDateTime.now());
            cutterLifeCycleRecord.setStatus(status);
            String operator = "";
            String content = "";
            if(status.equals(CutterLifeCycle.Status.getFresh)){ // 领新
                operator = "领取人："+JwtUtils.getLoginUsername();
                content = "领新单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.temporaryStorage)){ // 暂存
                operator = "归还人："+JwtUtils.getLoginUsername();
                content = "暂存单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.takeOut)){ // 取出
                operator = "取出人："+JwtUtils.getLoginUsername();
                content = "取出单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.tradeIn)){ // 以旧换新
                if(null != useBusinessType && useBusinessType.equals(UseInventoryInout.BusinessType.cellCabOutByOldNew)){ // 售刀柜领取(以旧换新)
                    operator = "领取人："+JwtUtils.getLoginUsername();
                    content = "新刀领新，领新单号："+code;
                }else if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.tempInByOldNew)){ // 以旧换新存入暂存
                    operator = "归还人："+JwtUtils.getLoginUsername();
                    content = "旧刀暂存，暂存单号："+code;
                }else if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.repairInByOldNew)){ // 以旧换新存入维修
                    operator = "归还人："+JwtUtils.getLoginUsername();
                    content = "旧刀报修，报修单号："+code;
                }else if(null != businessDetailType && businessDetailType.equals(StorageInventoryInout.BusinessDetailType.recycleInByOldNew)){ // 以旧换新存入报废
                    operator = "归还人："+JwtUtils.getLoginUsername();
                    content = "旧刀报废，报废单号："+code;
                }
            }else if(status.equals(CutterLifeCycle.Status.repair)){ // 报修
                operator = "归还人："+JwtUtils.getLoginUsername();
                content = "报修单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.scrap)){ // 报废
                operator = "归还人："+JwtUtils.getLoginUsername();
                content = "报废单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.loss)){ // 报失
                operator = "报失人："+JwtUtils.getLoginUsername();
                content = "报失单号："+code;
            }else if(status.equals(CutterLifeCycle.Status.check)){ // 盘验
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }else if(status.equals(CutterLifeCycle.Status.batchInUse)){ // 批量导入在用
                operator = "批量导入人："+JwtUtils.getLoginUsername();
                if(StringUtils.isNotBlank(deviceCode)){
                    content = "设备台机："+deviceCode;
                }
            }else if(status.equals(CutterLifeCycle.Status.batchReturn)){ // 批量还刀
                operator = "批量还刀人："+JwtUtils.getLoginUsername();
                if(StringUtils.isNotBlank(deviceCode)){
                    content = "设备台机："+deviceCode;
                }
            }else if(status.equals(CutterLifeCycle.Status.checkForTemporaryStorage)){ // 暂存(已盘验)
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }else if(status.equals(CutterLifeCycle.Status.checkForRepair)){ // 报修(已盘验)
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }else if(status.equals(CutterLifeCycle.Status.checkForScrap)){ // 报废(已盘验)
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }else if(status.equals(CutterLifeCycle.Status.checkForLoss)){ // 缺失(已盘验)
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }else if(status.equals(CutterLifeCycle.Status.checkForSpecDiscrepancy)){ // 规格不相符(已盘验)
                // 查询盘验信息设置内容
                operator = "盘验人："+JwtUtils.getLoginUsername();
                content = queryCheckedResult(code);
            }
            cutterLifeCycleRecord.setOperator(operator);
            cutterLifeCycleRecord.setContent(content);
            cutterLifeCycleRecordService.save(cutterLifeCycleRecord);

            // 如果添加的是领新的记录就要再添加在用的记录
            if(status.equals(CutterLifeCycle.Status.getFresh) || status.equals(CutterLifeCycle.Status.takeOut)
                    || (status.equals(CutterLifeCycle.Status.tradeIn) && null != useBusinessType && useBusinessType.equals(UseInventoryInout.BusinessType.cellCabOutByOldNew))){ // 领新 || 暂存取出 || 售刀柜领取(以旧换新)
                cutterLifeCycleRecord = new CutterLifeCycleRecord();
                cutterLifeCycleRecord.setCreator(JwtUtils.getLoginUserId());
                cutterLifeCycleRecord.setCreatorName(JwtUtils.getLoginUsername());
                cutterLifeCycleRecord.setCutterLifeCycleId(cutterLifeCycle.getId());
                cutterLifeCycleRecord.setStatus(CutterLifeCycle.Status.inUse);
                content = "";
                if(StringUtils.isNotBlank(deviceCode)){
                    content = "设备台机："+deviceCode;
                }
                cutterLifeCycleRecord.setContent(content);
                cutterLifeCycleRecordService.save(cutterLifeCycleRecord);
            }
        }
    }

    private String queryCheckedResult(String code) {
        // 通过盘验单号查询盘验信息
        CheckedResult checkedResult = checkedResultService.getOne(new QueryWrapper<CheckedResult>().eq("code", code));
        String result = "";
        if(checkedResult.getIsCorrect()){
            result = "结果相符("+checkedResult.getBusinessTypeDesc()+")";
        }else{
            result = "结果不相符("+checkedResult.getBusinessTypeDesc()+")";
        }
        return result+"，盘验单号："+code;
    }
}
